<?php

namespace app\admin\model\scanwork;

use think\Model;
use traits\model\SoftDelete;

/**
 * BOM模型
 */
class Bom extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'scanwork_bom';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    
    // 追加属性
    protected $append = [
        'bom_type_text',
        'status_text'
    ];

    /**
     * BOM类型列表
     */
    public function getBomTypeList()
    {
        return [
            1 => __('生产BOM'),
            2 => __('设计BOM'),
            3 => __('销售BOM')
        ];
    }

    /**
     * 状态列表
     */
    public function getStatusList()
    {
        return [
            0 => __('草稿'),
            1 => __('审核中'),
            2 => __('已发布'),
            3 => __('已归档')
        ];
    }

    /**
     * BOM类型文本
     */
    public function getBomTypeTextAttr($value, $data)
    {
        $value = $value ?? $data['bom_type'] ?? '';
        $list = $this->getBomTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?? $data['status'] ?? '';
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 关联产品
     */
    public function product()
    {
        return $this->belongsTo('Product', 'product_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联产品型号
     */
    public function model()
    {
        return $this->belongsTo('ProductModel', 'model_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联BOM明细
     */
    public function items()
    {
        return $this->hasMany('BomItem', 'bom_id', 'id');
    }

    /**
     * 关联创建人
     */
    public function creator()
    {
        return $this->belongsTo('app\admin\model\Admin', 'creator_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联审核人
     */
    public function approver()
    {
        return $this->belongsTo('app\admin\model\Admin', 'approver_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 生成BOM编号
     */
    public static function generateBomNo()
    {
        $prefix = 'BOM-';
        $date = date('Ymd');
        $lastBom = self::where('bom_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->value('bom_no');
        
        if ($lastBom) {
            $lastNum = intval(substr($lastBom, -4));
            $newNum = str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNum = '0001';
        }
        
        return $prefix . $date . $newNum;
    }

    /**
     * 计算BOM总成本
     */
    public function calculateCost()
    {
        $items = $this->items()->select();
        $totalCost = 0;
        
        foreach ($items as $item) {
            $totalCost += $item->total_price;
        }
        
        return $totalCost;
    }

    /**
     * 获取BOM树形结构
     */
    public function getBomTree($bomId = null)
    {
        $bomId = $bomId ?: $this->id;
        
        $items = BomItem::where('bom_id', $bomId)
            ->order('level', 'asc')
            ->order('sequence', 'asc')
            ->select();
        
        return $this->buildTree($items, 0);
    }

    /**
     * 构建树形结构
     */
    private function buildTree($items, $parentId = 0)
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item->parent_id == $parentId) {
                $node = $item->toArray();
                $children = $this->buildTree($items, $item->id);
                if ($children) {
                    $node['children'] = $children;
                }
                $tree[] = $node;
            }
        }
        return $tree;
    }

    /**
     * 复制BOM
     */
    public function copyBom($newVersion = null)
    {
        $newBom = $this->toArray();
        unset($newBom['id']);
        $newBom['bom_no'] = self::generateBomNo();
        $newBom['version'] = $newVersion ?: ($this->version + 0.1);
        $newBom['status'] = 0; // 草稿状态
        $newBom['createtime'] = time();
        $newBom['updatetime'] = time();
        
        $newBomModel = self::create($newBom);
        
        // 复制BOM明细
        $items = $this->items()->select();
        foreach ($items as $item) {
            $newItem = $item->toArray();
            unset($newItem['id']);
            $newItem['bom_id'] = $newBomModel->id;
            BomItem::create($newItem);
        }
        
        return $newBomModel;
    }
}

